<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="父级资源" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入父级资源"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="资源别名" prop="alias">
        <el-input
          v-model="queryParams.alias"
          placeholder="请输入资源别名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="资源类型" prop="category">
        <!--        <el-input-->
        <!--          v-model="queryParams.category"-->
        <!--          placeholder="请输入资源类型"-->
        <!--          clearable-->
        <!--          @keyup.enter="handleQuery"-->
        <!--          class="!w-240px"-->
        <!--        />-->

        <el-select
          v-model="queryParams.category"
          placeholder="请选择资源类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in ResourceTypesDicData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['res:center:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['res:center:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
        <el-button type="danger" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" />
          展开/折叠
        </el-button>
        <!--        <EFIconSelect v-model="queryParams.icon" />-->
        <!--        <IconSelect v-model="queryParams.icon" />-->
        <!--                <EFColorPicker v-model="queryParams.icon" />-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
      <template #name="{ row }">
        <!--        <EFIconSelect v-if="row.icon && Object.keys(row.icon).length" v-model="row.icon"/>-->
        <!--        <script>-->
        <!--          const iconData = JSON.parse(row.icon);-->
        <!--        </script>-->
        <!--        <EfIcon :icon="iconData.name" :size="iconData.size" :color="iconData.color" />-->

        <EFIconSelect
          v-model="row.icon"
          :editable="false"
          @update:model-value="(newVal) => handleUpdateModelValue(newVal, row)"
        />
        <!--        <EfIcon v-bind="row.icon" />-->
        <span>{{ row.name }}</span>
      </template>
      <template #runningStatus="{ row }">
        <el-tag v-if="row.status === 0" type="danger">已修改</el-tag>
        <el-tag v-else-if="row.status === -1" type="danger">已发布</el-tag>
        <el-tag v-else>禁用</el-tag>
      </template>
      <template #deployStatus="{ row }">
        <el-tag v-if="row.status === 0" type="success">正常</el-tag>
        <el-tag v-else-if="row.status === -1" type="danger">禁用</el-tag>
        <el-tag v-else>禁用</el-tag>
      </template>
      <template #category="{ row }">
        <el-tag> {{ ResourceAttrUtil.getResAttrByCategory(row.category).label }}</el-tag>

        <!--        <el-select-->
        <!--          v-model="row.category"-->
        <!--          placeholder="请选择资源类型"-->
        <!--          clearable-->
        <!--          class="!w-240px"-->
        <!--        >-->
        <!--          <el-option-->
        <!--            v-for="item in ResourceTypesDicData"-->
        <!--            :key="item.value"-->
        <!--            :label="item.label"-->
        <!--            :value="item.value"-->
        <!--          />-->
        <!--        </el-select>-->
      </template>
      <template #action="{ row }">
        <!--        <vxe-button mode="text" status="error" icon="vxe-icon-delete" permission-code="dictManageActionDelete" @click="removeRow(row)"></vxe-button>-->

        <span class="res-center-action">
          <el-button
            link
            type="primary"
            @click="openForm('update', row.id)"
            v-hasPermi="['res:center:update']"
          >
            编辑
          </el-button>

          <el-button link type="info" @click="addSubForm(row)" v-hasPermi="['res:center:update']">
            新增子项
          </el-button>

          <el-button
            link
            type="danger"
            @click="handleDelete(row.id)"
            v-hasPermi="['res:center:delete']"
          >
            删除
          </el-button>

          <template v-if="showButtons">
            <component
              v-for="(item, itemIndex) in ResourceAttrUtil.getResAttrByCategory(row.category)
                .actBtn"
              :key="itemIndex"
              :is="item.component || 'el-button'"
              v-bind="getComponentProps(item, row)"
              @click.stop.prevent="() => handleAction(item, row)"
            >
              <Icon v-if="item.icon" :icon="item.icon" />
              {{ t(item.text) }}
            </component>
          </template>
        </span>
      </template>
    </vxe-grid>

    <!-- 分页 -->
    <!--    <Pagination-->
    <!--      :total="total"-->
    <!--      v-model:page="queryParams.pageNo"-->
    <!--      v-model:limit="queryParams.pageSize"-->
    <!--      @pagination="getList"-->
    <!--    />-->
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CenterForm ref="formRef" @success="getList" />
  <!-- 设计弹窗 -->
  <ActionDesigner ref="actionDesignRef" />
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
// import { dateFormatter } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import download from '@/utils/download'
import { CenterApi, CenterVO } from '@/api/res/ResCenter'
import CenterForm from './CenterForm.vue'

import { VxeGridInstance, VxeGridListeners, VxeGridProps, VxeTablePropTypes } from 'vxe-table'

// import { DICT_TYPE } from '@/utils/dict'
import { ResourceAttrUtil, ResourceTypesDicData } from '@/api/res/ResCenter/ResourceCtrl'
import EFIconSelect from '@/components/Icon/src/EFIconSelect.vue'
import ActionDesigner from '@/components/res/designer/ActionDesign.vue'
// import { Vue3ColorPicker } from '@cyhnkckali/vue3-color-picker'
import '@cyhnkckali/vue3-color-picker/dist/style.css'
import { IconData } from '@/components/Icon'
import { getComponentProps } from '@/api/res/ResCenter/ResActBtns'

/** 资源中心 列表 */
defineOptions({ name: 'ResCenter' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const showButtons = ref(false)
const loading = ref(true) // 列表的加载中
const list = ref<CenterVO[]>([]) // 列表的数据
const queryParams = reactive({
  parentId: undefined,
  code: undefined,
  name: undefined,
  alias: undefined,
  path: undefined,
  source: undefined,
  sort: undefined,
  category: undefined,
  action: undefined,
  isOpen: undefined,
  remark: undefined,
  createDept: undefined,
  createTime: [],
  status: undefined,
  icon: undefined,
  pageNo: 1,
  pageSize: 10
})

// 查询条件
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const dsgnItem = ref<CenterVO>(null) // 设计器的item
const actionItem = ref<any>(null) // 设计器的item

const showText = ref(false)

/** 查询列表 */
const getList = async () => {
  loading.value = true

  try {
    const data = await CenterApi.getCenterList(queryParams)
    // gridRef.data = data
    gridOptions.data = data

    const treeData = handleTree(data, 'id', 'parentId', 'children')
    list.value = treeData

    setTimeout(() => {
      gridExpand(true)
    }, 300)
    // gridOptions.data = treeData
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const handleUpdateModelValue = (newVal, centVo) => {
  centVo.icon = newVal
  CenterApi.updateCenter(centVo).then((res) => {
    {
      message.success('更新成功')
    }
  })
}
/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const addSubForm = (row: CenterVO) => {
  formRef.value.addSubItem(row, () => {
    // gridExpand(true);
  })

  // setTimeout(() => {
  //   /** 展开/折叠操作 */
  //   gridExpand(true);
  // }, 1000)
}

const iconDataParse = (iconJsonStr: string): IconData => {
  try {
    return JSON.parse(iconJsonStr) as IconData // 使用类型断言
  } catch (e) {
    console.error('无效的 JSON 格式', e)
    return { name: '', size: '32px', color: 'red' } // 返回默认值
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CenterApi.deleteCenter(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const actionDesignRef = ref()

const handleAction = async (item: any, row: CenterVO) => {
  try {
    //
    dsgnItem.value = row
    actionItem.value = item

    if (item.methodName) {
      item.methodName.apply(null, [item, row])
    }
    if (item.cmp) {
      await nextTick() // 等待 DOM 更新
      if (actionDesignRef.value) {
        // actionDesignRef.value?.$emit('designerOpen', row, item);
        actionDesignRef.value?.designerOpen(row, item)
      }
    }

    // emit('handleAction',row,item)
    // // 二次确认 确认按钮   取消按钮
    // const confirm = await message.confirm(t('res.center.actionConfirm', [t(item.text)]))
    // if (confirm) {
    //   const res = await CenterApi.actionCenter(item.code, row.id) // 调用接口
    //   message.success(t('res.center.actionSuccess', [t(item.text)]))
    //   // 刷新列表
    //   await getList()
    // }
  } catch (ex) {
    console.log(ex)
  }
}
//
// const addSubItem = (dsgnObj: CenterVO, actItem: any) => {
//
//   alert('addSubItem')
// }
//
// provide('addSubItem', addSubItem)  // 提供给子组件使用

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CenterApi.exportCenter(queryParams)
    download.excel(data, '资源中心.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 展开/折叠操作 */
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const toggleExpandAll = async () => {
  // refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  // await nextTick()
  // refreshTable.value = true

  gridRef.value.setAllTreeExpand(isExpandAll.value)
}
const gridExpand = (checked: boolean) => {
  isExpandAll.value = checked

  gridRef.value.setAllTreeExpand(checked)
}

const sortedList = ref<CenterVO[]>([])
watch(list, (newList) => {
  sortedList.value = newList // 当原始列表变化时更新排序列表
})

const onEnd = (evt: any) => {
  // evt.newIndex 是排序后的新位置
  const movedItem = sortedList.value.splice(evt.oldIndex, 1)[0]
  sortedList.value.splice(evt.newIndex, 0, movedItem)
  // 在这里可以将新的排序结果保存到服务器...

  debugger
}

const gridRef = ref<VxeGridInstance<CenterVO>>()

const gridOptions = reactive<VxeGridProps<CenterVO>>({
  // border: true,
  rowConfig: {
    drag: true,
    isCurrent: true,
    isHover: true
  },
  rowDragConfig: {
    isSelfToChildDrag: true,
    isToChildDrag: true,
    isCrossDrag: true,
    isPeerDrag: true,
    showGuidesStatus: true
  },
  columnConfig: {
    drag: true,
    resizable: true
  },
  treeConfig: {
    transform: true,
    rowField: 'id',
    parentField: 'parentId',
    expandAll: isExpandAll,
    reserve: true
  },
  columnDragConfig: reactive<VxeTablePropTypes.ColumnDragConfig<CenterVO>>({
    visibleMethod({ column }) {
      if (column.field === 'name') {
        return true
      }
      return false
    }
    // disabledMethod({ column }) {
    //   if (column.field === 'name') {
    //     return false
    //   }
    //   return true
    // }
  }),
  columns: [
    { type: 'seq', width: 70 },
    // { field: 'icon', title: '', width: 40, slots: { default: 'icon' } },
    {
      field: 'name',
      title: '名称',
      minWidth: 300,
      treeNode: true,
      dragSort: true,
      sortable: true,
      slots: { default: 'name' }
    },
    { field: 'category', title: '类别', slots: { default: 'category' } },
    // { field: 'sort', title: '排序', width: 80, align: 'center', sortable: true },
    { field: 'status', title: '发布状态', width: 80, slots: { default: 'deployStatus' } },
    { field: 'status', title: '运行状态', width: 80, slots: { default: 'runningStatus' } },
    { field: 'action', title: '操作', fixed: 'right', minWidth: 180, slots: { default: 'action' } }
  ]
})

// 提取需要的字段并映射成 Java 类格式
const mapToJavaClass = (data: any[]) => {
  return data.map((item) => ({
    id: item.id,
    name: item.name,
    sort: item.sort,
    parentId: item.parentId,
    children: item.children ? mapToJavaClass(item.children) : []
  }))
}
const gridEvents: VxeGridListeners<CenterVO> = {
  rowDragstart({ row }) {
    console.log(`拖拽开始 ${row.name}`)
  },
  rowDragend({ newRow, oldRow, dragPos, offsetIndex, _index }) {
    debugger
    //保存排序结果
    const gridRefThat = gridRef.value
    const mappedData = mapToJavaClass(gridRefThat.getFullData())
    CenterApi.dragRowSort(mappedData).then((res) => {
      message.success(t('common.updateSuccess'))
    })
    // console.log(`拖拽完成，被拖拽行：${oldRow.name+"_"+oldRow.sort} 目标行：${newRow.name+"_"+newRow.sort} 目标位置：${dragPos}`)
  }
}

// ... existing code ...

/** 初始化 **/
onMounted(() => {
  getList()
  showButtons.value = true
})
</script>

<style lang="scss">
.res-center-action {
  el-button {
    cursor: pointer;
  }
}

.iconAction {
  display: flex;
  align-items: center;

  a {
    height: 63px;
    padding: 0 20px;
    width: 80px;
    display: flex;
    align-items: center;

    .iconBlock {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      align-items: center;
      height: 30px;

      span {
        display: inline-block;
        height: 30px;
        line-height: 30px;
        font-size: 16px;
        color: #7d33ff;
        font-weight: 500;
      }

      img {
        transition: all 0.2s linear;
      }

      &:hover {
        img {
          margin-top: -30px;
        }
      }
    }
  }

  img {
    width: 30px;
    vertical-align: middle;
  }
}

.flex-align-center {
  display: flex;
  //margin-left:12px;
  align-items: center;
}

.resIcon {
  .selector {
    display: contents;
  }
}
.el-drawer__body{
  padding: 0;
}
</style>
